import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store/index";
import { Loading } from "element-ui";
// @ts-ignore
import { path } from "@/api/login";

Vue.use(VueRouter);
let loadingInstance: any = null;
const routes = [
  {
    path: "/",
    redirect: {
      name: "login"
    }
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/login.vue") // 路由懒加载写法
  }
];
const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes: routes //配置路由
});
/* 路由拦截器 路由跳转前的操作 */
// to:表示要跳转的路由对象
// from:表示跳转前的路由对象
// next:继续执行跳转的函数，只有跳转前的拦截才有这个参数。
router.beforeEach((to, from, next) => {
  /* 路由跳转前可进行各种操作，如数据处理，权限验证，取消上页所有网络请求等等，
   *一定要注意，数据处理后，一定要执行next(),否则路由不会进行跳转。*/
  let text = "刷新页面";
  console.log(to.path);
  if (to.name == null && from.name == null) {
    loadingInstance = Loading.service({
      text: text,
      spinner: "el-icon-loading"
    });
  }
  if (to.name === "login") {
    next();
  } else {
    if (store.state.routerLength === 0) {
      path({}).then(() => {
        next({ path: to.path });
      });
    } else {
      next();
    }
  }
});
/* 路由拦截器 路由跳转后的操作 */
router.afterEach(to => {
  // 在这里执行路由跳转成功后所进行的操作
  //console.log("to", to.matched);
  if (loadingInstance != null) {
    loadingInstance.close();
  }
});

export default router;
